package net.feixue.engine.atomjob;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by zxxiao on 14/12/31.
 */
public class EngineWorker {
    private static final Logger logger = LoggerFactory.getLogger(EngineWorker.class);
    private static ExecutorService executor = Executors.newFixedThreadPool(50);

    private static AtomicLong taskSize = new AtomicLong();

    private static final long maxTask = 1000;

    public static void addJob(EngineJob job, EngineJobNotify notify) {
        job.setJobNotify(notify);
        checkTaskNum(job);

        for(EngineTask task : job.getTaskList()) {
            executor.execute(task);
        }
    }

    public static EngineFuture addJob(EngineJob job) {
        EngineFuture future = new EngineFuture();

        if (job.getTaskList().size() == 0) {
            future.setFinish(true);
            return future;
        }
        checkTaskNum(job);
        job.setFuture(future);

        for(EngineTask task : job.getTaskList()) {
            executor.execute(task);
        }
        return future;
    }

    /**
     * 检查现有任务队列，是否还有空间，没有则同步阻塞住
     * @param job
     */
    private synchronized static void checkTaskNum(EngineJob job) {
        while (taskSize.get() + job.getTaskList().size() > maxTask) {
            try {
                Thread.sleep(10);
                logger.info("engine task is full! please waiting 10ms.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        EngineWorker worker = new EngineWorker();
        EngineJob job = new EngineJob();
        for(int i = 0; i < 100; i++) {
            final int finalI = i;
            job.addTask(new EngineTask(finalI) {
                @Override
                public void doJob() {
                    System.err.println("now we print num is:" + finalI);
                }
            });
        }
        worker.addJob(job, new EngineJobNotify() {
            @Override
            public void doNotify() {
                System.out.println("all job is finish!");
            }
        });
    }
}
